/*
 * @Description: 路由权限配置
 *
 * @Date: 2021-03-11 15:25:34
 */
import router from './index'
import NProgress from 'nprogress' // 跳转进度条
import store from '@/store'
// 动态路由设置start

// 一定注册路由
let mustRouteArr = []
// 动态创建路由
// 处理组成菜单接口 以接口权限去判断
const verRoute = (data, hasPower) => {
	for (let i = 0; i < data.length; i++) {
		let elem = data[i]
		if (!elem.meta || !hasPower.some((item) => item.code == elem.meta.identifier)) {
			data.splice(i, 1)
			i--
			continue
		}
		if (elem.children && elem.children.length) {
			verRoute(elem.children, hasPower)
			if (!elem.children.length) {
				data.splice(i, 1)
				i--
				continue
			}
		}
	}
	return data
}
// 动态创建路由
const createDynamic = (hasPower) => {
	// 动态路由
	let arr = verRoute(mustRouteArr, hasPower)
	router.addRoutes(arr)
	console.log('createDynamic', arr)
	// 必有路由
	// router.addRoutes(mustRouteArr)
}

// 动态路由设置end
NProgress.configure({ showSpinner: false })
// 设置网页标题
function setDocumentTitle(title) {
	if (document && title) {
		document.title = title
	}
}

// 免登录路由
const whiteList = ['/401', '/iamErr', '/mobileErr']

// 处理多级路由缓存
function handleKeepAlive(to) {
	if (to.matched && to.matched.length > 2) {
		for (let i = 0; i < to.matched.length; i++) {
			const element = to.matched[i]
			if (element.components.default.name === 'Layout') {
				to.matched.splice(i, 1)
				handleKeepAlive(to)
			}
		}
	}
}

// 通过colId找到顶级路由title
function findTopNavMenuTitle(colId, navId) {
	let currentItem = store.getters.levelMenus.find(e => {
		if (e.colId == colId) {
			return e
		}
	})
	if (!currentItem) {
		currentItem = store.getters.levelMenus.find(e => {
			if (e.colId == navId) {
				return e
			}
		})
		colId = navId
	}
	if (currentItem) {
		if (currentItem.colParentId == -1) {
			return currentItem
		}
		const parentNav = store.getters.levelMenus.find(e => {
			if (currentItem.colParentId == e.colId) {
				return e
			}
		})
		return parentNav
	}
}

// 拦截路由处理生产环境
router.beforeEach(async (to, from, next) => {
	// 处理多级路由缓存
	// handleKeepAlive(to)
	const hasToken = true //getToken()
	NProgress.start()
	if (to.query.title) {
		to.meta.title = decodeURIComponent(to.query.title)
	}
	if (to.path.indexOf('/list') != -1 && to.query.colId) {
		let routes = router.options.routes
		for (let index = 0; index < routes.length; index++) {
			const element = routes[index];
			const parentNav = findTopNavMenuTitle(to.query.colId, to.query.navId)
			if (element.redirect == '/list' || element.redirect == '/navlist') {
				console.log('router.beforeEach:', parentNav, element)
				element.meta.title = parentNav ? parentNav.colTitle : to.meta.title
				break
			}
		}
	}

	setDocumentTitle(to.meta.title)

	// 如果已经登录
	if (hasToken) {
		next()
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			next()
		} else {
			next(`/401`)
		}
	}
})

// 跳转完成
router.afterEach(() => {
	// console.log('跳转完成=>')
	NProgress.done()
})

export default createDynamic
